# /bin/bash

if test -d ./postgres; then
    echo "位于正确的目录"
else
    echo "缺少postgres目录,请检查是否位于正确的目录"
    exit 1
fi

# 新建一个docker网络
echo "新建docker网络"
docker network create --subnet=172.18.0.0/16 yoga-network
if [ $? -ne 0 ];then
    echo "新建docker网络失败"
    exit 1
fi

# 进行构建postgres ----------------------------------------------
cd ./postgres
docker build -t postgresyoga .
if [ $? -ne 0 ];then
    echo "构建postgres失败"
    exit 1
fi

docker run -d --name postgresYoga --network yoga-network --ip 172.18.0.5 postgresyoga
if [ $? -ne 0 ];then
    echo "创建数据库容器失败"
    exit 1
fi
docker start postgresYoga
if [ $? -ne 0 ];then
    echo "启动数据库容器失败"
    exit 1
fi

# 进行构建api -------------------------------------------------
if test -d ../../apiYoga ;then
    echo " 开始构建golang api"
    cd ../../apiYoga
        else
    echo "缺少apiYoga目录,请检查是否位于正确的目录"
    exit 1
fi
docker build -t apiyoga .
if [ $? -ne 0 ];then
    echo "构建golang api失败"
    exit 1
fi
docker start postgresYoga
if [ $? -ne 0 ];then
    echo "启动数据库容器失败"
    exit 1
fi

docker run -d --name apiYoga --network yoga-network --ip 172.18.0.6 apiyoga
if [ $? -ne 0 ];then
    echo "创建api容器失败"
    exit 1
fi

docker start apiYoga
if [ $? -ne 0 ];then
    echo "启动后端程序失败"
    exit 1
fi


# 进行构建nginx  ---------------------------------------------------------
if test -d ../部署/nginx; then
    echo " 开始构建nginx"
    cd ../部署/nginx
    else
    echo "缺少nginx目录,请检查是否位于正确的目录"
    exit 1
fi

docker build -t nginxyoga .
if [ $? -ne 0 ];then
    echo "构建nginx失败"
    exit 1
fi
docker run -d --name nginxYoga --network yoga-network -p 80:80 -v ./conf/nginx.conf:/etc/nginx/nginx.conf  nginxyoga
if [ $? -ne 0 ];then
    echo "创建nginx容器失败"
    exit 1
fi
docker start apiYoga
if [ $? -ne 0 ];then
    echo "启动后端程序失败"
    exit 1
fi
echo "构建成功"
echo "请使用 curl http://localhost:80   确认nginx运行正常"
echo "运行 curl http://localhost:80/api/ping2 确认golang后端程序运行正常"